package edu.hwadee.BEIS.controller;

import javax.servlet.http.HttpSession;

import edu.hwadee.BEIS.dto.*;
import edu.hwadee.BEIS.entity.*;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSON;

import edu.hwadee.BEIS.constants.ResultEnum;
import edu.hwadee.BEIS.util.ResultUtil;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashSet;

/**
 * @author kingsong
 * @create 2018/8/15 9:34
 * @desc 系统管理Controller
 **/
@RestController
@RequestMapping("/management")
public class SystemManageController extends BaseController {

    /**
     * 注册第一步：输入注册凭证
     *
     * @param userType
     * @param code
     * @return
     */
    @PostMapping(value = "/register/1", produces = "application/json;charset=utf-8")
    public String register_1(String userType, String code) {
        JsonResult res = ResultUtil.success();

        if (!systemManageService.validCertificate(userType, code)) {
            res = ResultUtil.error(ResultEnum.CERTIFICATE_WRONG);
        }
        return res.toString();
    }

    /**
     * 注册第二步(学校用户)：判断学校是否已经存在
     *
     * @param school_id
     * @return
     */
    @PostMapping(value = "/register/2/school", produces = "application/json;charset=utf-8")
    public String register_2_school(String school_id) {
        JsonResult res = ResultUtil.success();

        if (systemManageService.schoolIsExisted(school_id)) {
            res = ResultUtil.error(ResultEnum.SCHOOL_ISEXITED);
        }
        return res.toString();
    }

    /**
     * 注册第二步(区县用户)：判断行政编号是否已经存在
     *
     * @param adminCode
     * @return
     */
    @PostMapping(value = "/register/2/county", produces = "application/json;charset=utf-8")
    public String register_2_county(String adminCode) {
        JsonResult res = ResultUtil.success();

        if (systemManageService.adminCodeIsBeenUsed(adminCode)) {
            res = ResultUtil.error(ResultEnum.ADMINCODE_ISBEENUSED);
        }
        return res.toString();
    }

    /**
     * 注册第二步(市局用户)：判断行政编号是否已经存在
     *
     * @param adminCode
     * @return
     */
    @PostMapping(value = "/register/2/city", produces = "application/json;charset=utf-8")
    public String register_2_city(String adminCode) {
        JsonResult res = ResultUtil.success();

        if (systemManageService.adminCodeIsBeenUsed(adminCode)) {
            res = ResultUtil.error(ResultEnum.ADMINCODE_ISBEENUSED);
        }
        return res.toString();
    }

    /**
     * 注册第三步（学校用户）：封装信息，保存账号
     *
     * @param schoolUserInfor
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/register/3/school", produces = "application/json;charset=utf-8")
    public String register_3_school(SchoolUserDTO schoolUserInfor, HttpSession session) throws Exception {
        JsonResult res = ResultUtil.success();
        SchoolUser schoolUser = systemManageService.schoolUserInfor2Object(schoolUserInfor);

        systemManageService.register(schoolUser);
        session.setAttribute("user_id", schoolUser.getSchoolUserId());
        session.setAttribute("user_type", "1");
        return res.toString();
    }

    /**
     * 注册第三步（区县用户）：封装信息，保存账号
     *
     * @param countyUserInfor
     * @param session
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/register/3/county", produces = "application/json;charset=utf-8")
    public String register_3_county(CountyUserDTO countyUserInfor, HttpSession session) throws Exception {
        JsonResult res = ResultUtil.success();

        if (systemManageService.countyUserIsExisted(countyUserInfor.getCountyUserId())) {
            // 区县用户名已存在
            res = ResultUtil.error(ResultEnum.COUNTYUSER_ISEXISTED);
        }
        systemManageService.register(countyUserInfor);
        session.setAttribute("user_id", countyUserInfor.getCountyUserId());
        session.setAttribute("user_type", "3");
        return res.toString();
    }

    /**
     * 注册第三步（市局用户）：封装信息，保存账号
     *
     * @param cityUserInfor
     * @param session
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/register/3/city", produces = "application/json;charset=utf-8")
    public String register_3_city(CityUserDTO cityUserInfor, HttpSession session) throws Exception {
        JsonResult res = ResultUtil.success();

        if (systemManageService.cityUserIsExisted(cityUserInfor.getCityUserId())) {
            // 市局用户名已存在
            res = ResultUtil.error(ResultEnum.CITYUSER_ISEXISTED);
        }
        systemManageService.register(cityUserInfor);
        session.setAttribute("user_id", cityUserInfor.getCityUserId());
        session.setAttribute("user_type", "3");
        return res.toString();
    }

    /**
     * 注册第三步（高级用户）：封装信息，保存账号
     *
     * @param leaderUserInfor
     * @param session
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/register/3/leader", produces = "application/json;charset=utf-8")
    public String register_3_leader(LeaderUserDTO leaderUserInfor, HttpSession session) throws Exception {
        JsonResult res = ResultUtil.success();

        if (systemManageService.cityUserIsExisted(leaderUserInfor.getLeaderUserId())) {
            // 高级用户名已存在
            res = ResultUtil.error(ResultEnum.LEADERUSER_ISEXISTED);
        }
        systemManageService.register(leaderUserInfor);
        session.setAttribute("user_id", leaderUserInfor.getLeaderUserId());
        session.setAttribute("user_type", "3");
        return res.toString();
    }

    /**
     * 登录
     *
     * @param user_type 账户类型
     * @param user_id   用户ID
     * @param pwd       密码
     * @param session   会话
     * @return
     */
    @PostMapping(value = "/login", produces = "application/json;charset=utf-8")
    public String login(String user_type, String user_id, String pwd, HttpSession session) {
        JsonResult res = ResultUtil.success();

        if (!systemManageService.login(user_type, user_id, pwd)) {
            res = ResultUtil.error(ResultEnum.USER_LOGIN_FAILURE);
        } else {
            session.setAttribute("user_id", user_id);
            session.setAttribute("user_type", user_type);
        }
        return res.toString();
    }

    @GetMapping(value = "/logout", produces = "application/json;charset=utf-8")
    public String logout(HttpSession session) {
        JsonResult res = ResultUtil.success();

        session.invalidate();

        return res.toString();
    }

    /**
     * 获取所有开放填报信息
     *
     * @return
     */
    @GetMapping(value = "/openmodify", produces = "applicaiton/json;charset=utf-8")
    public String getOpenModify() {
        JsonResult res = ResultUtil.success();

        res.setData(systemManageService.getAllOpenModify());

        return res.toString();
    }

    /**
     * 保存开放填报信息，使其生效
     *
     * @param openModifyInfor
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/openmodify", produces = "application/json;charset=utf-8")
    public String saveOpenModify(OpenModifyDTO openModifyInfor) throws Exception {
        JsonResult res = ResultUtil.success();

        OpenModify openModify = systemManageService.OpenModifyInfor2Object(openModifyInfor);
        systemManageService.saveOpenModify(openModify);

        return res.toString();
    }

    /**
     * 获取所有审核通过的项目申报信息
     *
     * @param pageable
     * @return
     */
    @PostMapping(value = "/project/all", produces = "application/json;charset=utf-8")
    public String getAllProjectDeclare(Pageable pageable) {
        JsonResult res = ResultUtil.success();

        res.setData(systemManageService.getAllProjectDeclare(pageable));

        return res.toString();
    }

    /**
     * 获取中央项目
     *
     * @param pageable
     * @return
     */
    @PostMapping(value = "/project/country", produces = "application/json;charset=utf-8")
    public String getCountryProjectDeclare(Pageable pageable) {
        JsonResult res = ResultUtil.success();

        res.setData(systemManageService.getCountryProjectDeclare(pageable));

        return res.toString();
    }

    /**
     * 获取省级项目
     *
     * @param pageable
     * @return
     */
    @PostMapping(value = "/project/province", produces = "application/json;charset=utf-8")
    public String getProvinceProjectDeclare(Pageable pageable) {
        JsonResult res = ResultUtil.success();

        res.setData(systemManageService.getProvinceProjectDeclare(pageable));

        return res.toString();
    }

    /**
     * 获取市级项目
     *
     * @param pageable
     * @return
     */
    @PostMapping(value = "/project/city", produces = "application/json;charset=utf-8")
    public String getCityProjectDeclare(Pageable pageable) {
        JsonResult res = ResultUtil.success();

        res.setData(systemManageService.getCityProjectDeclare(pageable));

        return res.toString();
    }

    /**
     * 上传项目分析图表
     *
     * @param analysisDiagramInfor
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/analysis_diagram", produces = "application/json;charset=utf-8")
    public String postAnalysisDiagram(AnalysisDiagramDTO analysisDiagramInfor) throws Exception {
        JsonResult res = ResultUtil.success();
        AnalysisDiagram analysisDiagram = systemManageService.analysisDiagramData2Object(analysisDiagramInfor);
        systemManageService.saveAnalysisDiagram(analysisDiagram);
        return res.toString();
    }

    /**
     * 通过项目申报ID获得其项目分析图表信息
     *
     * @param project_id 项目申报ID
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/analysis_diagram", produces = "application/json;charset=utf-8")
    public String getAnalysisDiagram(Integer project_id) throws Exception {
        JsonResult res = ResultUtil.success();
        res.setData(systemManageService.getAnalysisDiagramByProjectId(project_id));
        return res.toString();
    }

    /**
     * 删除项目分析图表
     *
     * @param analysisDiagram_id 分析图表ID
     * @return
     * @throws Exception
     */
    @DeleteMapping(value = "/analysis_diagram", produces = "application/json;charset=utf-8")
    public String deleteAnalysisDiagram(Integer analysisDiagram_id) throws Exception {
        JsonResult res = ResultUtil.success();
        systemManageService.deleteAnalysisDiagram(analysisDiagram_id);
        return res.toString();
    }

    /**
     * 获取所有凭证
     *
     * @return
     */
    @GetMapping(value = "/certificate", produces = "application/json;charset=utf-8")
    public String getCertificate() {
        JsonResult res = ResultUtil.success();
        res.setData(systemManageService.getAllCertificate());
        return res.toString();
    }

    /**
     * 保存凭证
     *
     * @param certificate
     * @return
     */
    @PostMapping(value = "/certificate", produces = "application/json;charset=utf-8")
    public String saveCertificate(Certificate certificate) {
        JsonResult res = ResultUtil.success();
        systemManageService.saveCertificate(certificate);
        return res.toString();
    }

    /**
     * 删除凭证
     *
     * @param certificateId 凭证编号
     * @return
     */
    @DeleteMapping(value = "/certificate", produces = "application/json;charset=utf-8")
    public String deleteCertificate(Integer certificateId) {
        JsonResult res = ResultUtil.success();
        systemManageService.deleteCertificate(certificateId);
        return res.toString();
    }

    /**
     * 分页获得所有学校用户
     *
     * @param pageable
     * @return
     */
    @PostMapping(value = "/schooluser", produces = "application/json;charset=utf-8")
    public String getSchoolUser(Pageable pageable) {
        JsonResult res = ResultUtil.success();
        res.setData(systemManageService.getAllSchoolUser(pageable));
        return res.toString();
    }

    /**
     * 分页获得所有区县用户
     *
     * @param pageable
     * @return
     */
    @PostMapping(value = "/countyuser", produces = "application/json;charset=utf-8")
    public String getCountyUser(Pageable pageable) {
        JsonResult res = ResultUtil.success();
        res.setData(systemManageService.getAllCountyUser(pageable));
        return res.toString();
    }

    /**
     * 分页获得所有市局用户
     *
     * @param pageable
     * @return
     */
    @PostMapping(value = "/cityuser", produces = "application/json;charset=utf-8")
    public String getCityUser(Pageable pageable) {
        JsonResult res = ResultUtil.success();
        res.setData(systemManageService.getAllCityUser(pageable));
        return res.toString();
    }

    /**
     * 分页获得所有高级用户
     *
     * @param pageable
     * @return
     */
    @PostMapping(value = "/leaderuser", produces = "application/json;charset=utf-8")
    public String getLeaderUser(Pageable pageable) {
        JsonResult res = ResultUtil.success();
        res.setData(systemManageService.getAllLeaderUser(pageable));
        return res.toString();
    }

    /**
     * 修改学校用户
     *
     * @param schoolUserInfor
     * @return
     */
    @PutMapping(value = "/schooluser", produces = "application/json;charset=utf-8")
    public String modifySchoolUser(SchoolUserDTO schoolUserInfor) {
        JsonResult res = ResultUtil.success();
        systemManageService.modifySchoolUser(schoolUserInfor);
        return res.toString();
    }

    /**
     * 修改区县用户
     *
     * @param countyUserInfor
     * @return
     */
    @PutMapping(value = "/countyuser", produces = "application/json;charset=utf-8")
    public String modifyCountyUser(CountyUserDTO countyUserInfor) {
        JsonResult res = ResultUtil.success();
        systemManageService.modifyCountyUser(countyUserInfor);
        return res.toString();
    }

    /**
     * 修改市局用户
     *
     * @param cityUserInfor
     * @return
     */
    @PutMapping(value = "/cityuser", produces = "application/json;charset=utf-8")
    public String modifyCityUser(CityUserDTO cityUserInfor) {
        JsonResult res = ResultUtil.success();
        systemManageService.modifyCityUser(cityUserInfor);
        return res.toString();
    }

    /**
     * 修改高级用户
     *
     * @param leaderUserInfor
     * @return
     */
    @PutMapping(value = "/leaderuser", produces = "application/json;charset=utf-8")
    public String modifyLeaderUser(LeaderUserDTO leaderUserInfor) {
        JsonResult res = ResultUtil.success();
        systemManageService.modifyLeaderUser(leaderUserInfor);
        return res.toString();
    }

    /**
     * 修改密码：确认旧密码
     *
     * @param oldPwd
     * @param session
     * @return
     */
    @PostMapping(value = "/pwd", produces = "application/json;charset=utf-8")
    public String confirmPwd(String oldPwd, HttpSession session) {
        JsonResult res = ResultUtil.success();

        String user_id = (String) session.getAttribute("user_id");
        String user_type = (String) session.getAttribute("user_type");

        if (!systemManageService.login(user_type, user_id, oldPwd)) {
            res = ResultUtil.error(ResultEnum.USER_PSW_WRONG);
        }
        return res.toString();
    }

    /**
     * 修改密码：保存新密码
     *
     * @param newPwd
     * @param session
     * @return
     */
    @PutMapping(value = "/pwd", produces = "application/json;charset=utf-8")
    public String modifyPwd(String newPwd, HttpSession session) {
        JsonResult res = ResultUtil.success();
        String user_id = (String) session.getAttribute("user_id");
        String user_type = (String) session.getAttribute("user_type");
        if (!systemManageService.modifyPwd(user_type, user_id, newPwd)) {
            res = ResultUtil.error(ResultEnum.PWD_MODIFY_FALURE);
        }
        return res.toString();
    }

    /**
     * 文件下载
     *
     * @param filePath 文件绝对路径
     * @return
     */
    @GetMapping(value = "/download")
    public ResponseEntity<FileSystemResource> downloadFile(String filePath) {

        File file = new File(filePath);
        String filename = file.getName();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("charset", "utf-8");
        //设置下载文件名
        try {
            filename = URLEncoder.encode(filename, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        headers.add("Content-Disposition", "attachment;filename=\"" + filename + "\"");
        return ResponseEntity.ok().headers(headers).contentType(MediaType.parseMediaType("application/x-msdownload")).body(new FileSystemResource(file));
    }

    /**
     * 获取用户公告
     *
     * @param pageable 分页参数
     * @param session
     * @return
     */
    @PostMapping(value = "/announcement/school", produces = "application/json;charset=utf-8")
    public String getAllAnnouncement(Pageable pageable, HttpSession session) {
        JsonResult res = ResultUtil.success();

        res.setData(systemManageService.findSchoolUserAnnoucement(pageable, (String) session.getAttribute("user_id")));

        return res.toString();
    }

    /**
     * 发布公告
     *
     * @param annoucementDTO
     * @param session
     * @return
     */
    @PostMapping(value = "/announcement", produces = "application/json;charset=utf-8")
    public String publishAnnoucement(AnnoucementDTO annoucementDTO, HttpSession session) {
        JsonResult res = ResultUtil.success();
        systemManageService.publishAnnouncement(annoucementDTO, (String)session.getAttribute("user_id"));
        return res.toString();
    }
}
